<script setup>
import { onMounted, reactive, ref, watch } from "vue"
import { deleteTableDataApi, getTableDataApi, saveTableDataApi } from "@/api/product/product"
import { ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "productIndex"
})

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA = {
  title: "",
  product_id: 0
}

const dialogVisible = ref(false)
const formRef = ref(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {
  title: [{ required: true, trigger: "blur", message: "名称不能为空" }],
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row) => {
  ElMessageBox.confirm(`正在删除信息：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.product_id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref([])
const searchFormRef = ref(null)
const searchData = reactive({
  title: "",
})

const getTableData = () => {
  loading.value = true
  getTableDataApi({
    page: paginationData.currentPage,
    keyword: searchData.title
  })
    .then((data) => {
      paginationData.total = data.total
      tableData.value = data.items
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="title" label="关键字">
              <el-input v-model="searchData.title" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增商品</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" border>
          <el-table-column prop="product_code" label="编号" align="center" width="150" />
          <el-table-column prop="title" label="名称" align="left" width="260" />
          <el-table-column prop="demo" label="备注" align="left"  />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="formData.product_id === 0 ? '新增商品' : '修改商品'"
      @closed="resetForm" width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="title" label="名称" required>
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item prop="product_code" label="编号">
          <el-input v-model="formData.product_code" :disabled="formData.product_id !== 0 && formData.product_code != ''" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item prop="demo" label="备注">
          <el-input v-model="formData.demo" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
